package handler

def staticFileUrlPat = /.*\.(js|css|html|properties|groovy|xml|json)/
def staticImageUrlPat = /.*\.(jpg|jpeg|png|gif|ico|eot|svg|ttf|woff|swf)/
def staticFontUrlPat = /.*\.(eot|svg|ttf|woff|swf)/

// 静态文件，直接输出
handler.getRegEx(staticFileUrlPat){req, resp ->
	log.info('access ' + req.path)

	resp.sendFile config.webroot + req.path
}.getRegEx(staticImageUrlPat){req, resp ->
	log.info('access ' + req.path)

	String contentType = 'application/octet-stream'
	def mat = req.path =~ staticFontUrlPat
	if(!mat){
		mat = req.path =~ staticImageUrlPat
		String ext = mat ? mat[0][1] : 'jpg'
		contentType = 'image/' + ext
	}
	resp.headers.set('Content-Type', contentType)

	vertx.fileSystem.readFile(config.webroot + req.path){ar ->
		if(ar.succeeded){
			resp.chunked = true
			resp << ar.result
			resp.end()
		}else{
			resp.setStatusCode(404).end()
		}
	}
}.setNoMatchHandler{req, resp ->
	resp.statusCode = 404

	resp.sendFile config.webroot + '/static/404.html'
}.setErrorHandler{req, resp, ex ->
	log.error('', ex)
	resp.statusCode = 500

	resp.sendFile config.webroot + '/static/500.html'
}